import React, { useEffect, useRef } from 'react'
import * as echarts from 'echarts'
import { Card } from 'antd'
import { EChartsType } from 'echarts'

const BarChart: React.FC = () => {
  const chartRef: any = useRef() // 拿到DOM容器
  let myChart: EChartsType

  const initChart = () => {
    const chart = echarts.getInstanceByDom(chartRef.current)
    myChart = chart || echarts.init(chartRef.current)

    const option = {
      xAxis: {
        type: 'category',
        data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
      },
      yAxis: {
        type: 'value',
      },
      tooltip: {
        trigger: 'item',
      },
      series: [
        {
          data: [120, 200, 150, 80, 70, 110, 130],
          type: 'bar',
        },
      ],
    }

    option && myChart.setOption(option)
  }

  useEffect(() => {
    initChart()

    return () => {
      myChart && myChart.dispose()
    }
  }, [])

  return (
    <Card>
      <div ref={chartRef} style={{ width: '80%', margin: '0 auto', height: '600px' }} />
    </Card>
  )
}

export default BarChart
